18. Matplotlib库基础

引言:可视化的重要性

金融数据可视化在商业决策中扮演关键角色:

  • 发现模式:识别数据中的趋势、周期与异常
  • 沟通结果:图表比数字更直观,更易于被理解
  • 辅助决策:为交易决策提供有力的视觉支撑

Matplotlib 简介

  • Python 中最经典、最流行的绑图库
  • 提供 pyplot 模块,接口类似 MATLAB
  • 灵活度高,可定制图表的每一个元素
  • 是 Seaborn、Pandas 绑图等高级库的底层基础

基础绘图:核心流程

使用 Matplotlib 绑图的标准流程:

  1. 导入库import matplotlib.pyplot as plt
  2. 准备数据:使用 NumPy 或 Pandas 构造数据
  3. 创建画布/子图plt.figure()plt.subplots()
  4. 绑制图形plt.plot(), plt.bar()
  5. 设置元素:标题、轴标签、图例、网格
  6. 显示/保存plt.show()plt.savefig()

⭐ 平台任务:按揭贷款本息偿还

Listing 1
# ⚠️ 平台原始代码 - 请原样输入至教学平台(注释除外),平台才会判定答案正确
# 注:numpy_financial包本地未安装,但平台已经内置
import matplotlib.pyplot as plt  # 导入Matplotlib绑图库
plt.rcParams['font.family'] = 'SimHei'  # 设置Matplotlib全局参数
plt.rcParams['axes.unicode_minus'] = False  # 设置Matplotlib全局参数
import numpy_financial as npf  # 导入NumPy数值计算库
import numpy as np  # 导入NumPy数值计算库
r=0.05 # 贷款的年利率
n=30 # 贷款的年数
principle=8e6  # 设置期数/数量为8000000
pay_month=npf.ppmt(rate=r/12,per=n*12,nper=n*12,pv=principle,fv=0,when='end') #计算每月支付的本息之和
print('每月的偿还的金额',round(pay_month,2))  # 输出每月的偿还的金额
T_list=np.arange(n*12)+1 #生成一个包含每次还款期限的数组
# 计算每期应还的本金部分
prin_month=npf.ppmt(rate=r/12,per=T_list,nper=n*12,pv=principle,fv=0,when='end')
# 计算每期应还的利息部分
inte_month=npf.ipmt(rate=r/12,per=T_list,nper=n*12,pv=principle,fv=0,when='end')
pay_month_list=pay_month*np.ones_like(prin_month)  # 生成与prin_month等长的每月总还款额数组
fig=plt.figure(figsize=(9,6))  # 创建图形画布
ax=fig.add_subplot(111)  # 添加单个子图占据整个画布
ax.plot(T_list,-pay_month_list,'r-',label=u'每月偿还金额')  # 在子图上绑制曲线
ax.plot(T_list,-prin_month,'m--',label=u'每月偿还本金金额')  # 在子图上绑制曲线
ax.plot(T_list,-inte_month,'b--',label=u'每月偿还利息金额')  # 在子图上绑制曲线
ax.set_xlabel(u'逐次偿还的期限(月)',fontsize=14)  # 设置X轴标签
ax.set_ylabel(u'金额',fontsize=14)  # 设置Y轴标签
ax.legend()  # 设置图例
plt.savefig("1.png")  # 保存图形至文件

按揭贷款参数设定

Listing 2
# ==================== 导入必要的库 ====================
import matplotlib.pyplot as plt  # Matplotlib的pyplot模块
import numpy as np  # NumPy数值计算库

# ==================== 按揭贷款参数 ====================
# principal:贷款本金(100万元)
principal = 1000000
# rate:年利率(4.9%,典型商业贷款利率)
rate = 0.049
# years:贷款期限(30年)
years = 30

# ==================== 计算月供(等额本息) ====================
# monthly_rate:月利率 = 年利率 / 12
monthly_rate = rate / 12
# n_months:总月数 = 年数 * 12
n_months = years * 12
# 等额本息月供公式:M = P * [r(1+r)^n] / [(1+r)^n - 1]
monthly_payment = principal * (monthly_rate * (1 + monthly_rate)**n_months) / ((1 + monthly_rate)**n_months - 1)

print(f'月供: {monthly_payment:.2f}元')
print(f'总还款: {monthly_payment * n_months:.2f}元')
print(f'总利息: {monthly_payment * n_months - principal:.2f}元')
月供: 5307.27元
总还款: 1910616.19元
总利息: 910616.19元

逐年计算本金与利息

Listing 3
# ==================== 逐年计算本金和利息 ====================
years_array = np.arange(1, years + 1)
balance = principal  # 剩余本金
interest_paid = []   # 每年支付的利息
principal_paid = []  # 每年偿还的本金

for year in years_array:
    annual_interest = 0   # 当年累计利息
    annual_principal = 0  # 当年累计本金
    for _ in range(12):
        # 当月利息 = 剩余本金 × 月利率
        interest = balance * monthly_rate
        # 当月本金 = 月供 - 当月利息
        principal_part = monthly_payment - interest
        balance -= principal_part
        annual_interest += interest
        annual_principal += principal_part
    interest_paid.append(annual_interest)
    principal_paid.append(annual_principal)

绑制按揭贷款本息偿还图

# ==================== 绑图 ====================
plt.figure(figsize=(10, 6))
plt.plot(years_array, interest_paid, label='利息', linewidth=2)
plt.plot(years_array, principal_paid, label='本金', linewidth=2)

# ==================== 设置图表元素 ====================
plt.xlabel('年份', fontsize=12)
plt.ylabel('金额(元)', fontsize=12)
plt.title('按揭贷款30年本金利息分解', fontsize=14)
plt.legend(fontsize=12)
plt.grid(True, alpha=0.3)

# ==================== 添加注释 ====================
plt.annotate('前期利息占比高', xy=(5, interest_paid[4]),
             xytext=(10, interest_paid[4]),
             arrowprops=dict(arrowstyle='->'))
plt.tight_layout()
plt.show()
Figure 1: 按揭贷款本息偿还图

常见图表类型概览

Matplotlib 支持多种图表类型,满足不同数据展示需求:

图表类型 函数 适用场景
折线图 plt.plot() 时间序列、趋势变化
柱状图 plt.bar() 类别比较
散点图 plt.scatter() 变量关系、相关性
饼图 plt.pie() 占比分布

图表类型示例

import matplotlib.pyplot as plt
import numpy as np

# 创建2行2列的子图布局
fig, axes = plt.subplots(2, 2, figsize=(12, 10))

# ====== 1. 折线图 ======
x = np.linspace(0, 10, 100)
y = np.sin(x)
axes[0, 0].plot(x, y, linewidth=2)
axes[0, 0].set_title('折线图')
axes[0, 0].grid(True)

# ====== 2. 柱状图 ======
categories = ['A', 'B', 'C', 'D']
values = [20, 35, 30, 25]
axes[0, 1].bar(categories, values, color='steelblue')
axes[0, 1].set_title('柱状图')

# ====== 3. 散点图 ======
x = np.random.randn(100)
y = np.random.randn(100)
axes[1, 0].scatter(x, y, alpha=0.6)
axes[1, 0].set_title('散点图')
axes[1, 0].set_xlabel('X')
axes[1, 0].set_ylabel('Y')

# ====== 4. 饼图 ======
sizes = [30, 20, 25, 25]
labels = ['股票', '债券', '现金', '其他']
axes[1, 1].pie(sizes, labels=labels, autopct='%1.1f%%')
axes[1, 1].set_title('投资组合分布')

plt.tight_layout()
plt.show()
Figure 2: 常用图表类型示例

本章小结

  • Matplotlib 是 Python 数据可视化的核心基础库
  • 绑图标准流程:导入 → 数据 → 画布 → 绑图 → 设置 → 显示
  • 核心图表类型:折线图、柱状图、散点图、饼图
  • 重要元素:标题、轴标签、图例、网格、注释
  • 掌握 plt.subplots() 可灵活创建多子图布局